﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Net;
using System.IO;
using System.Text;

public class HTTPreq : MonoBehaviour {
    public GameObject GRID;
    public GameObject PREFAB;
    public  string content;

    //public Text message;

    public InputField inputName;
    public Button insertBtn;
    public Button reload;
    public GameObject window;
    public Text label;
    public bool responsIsSure=false;
    public GameObject windowInset;
    public GameObject inputError;
    public GameObject loding;
    public string str;
    string name;
    int count;
   string ip = "http://112.74.26.66:7788/";
    void Start() 
    {
        insertBtn.enabled = true;
        reload.enabled = true;
    }
    void Awake()
    {
      //  print("进入Awake");
        reqTop();
        Invoke("Showwindow",4f); 
        Invoke("messageDes",4f);
       // reload.enabled = false;
    }
    void Showwindow() 
    {
        label.gameObject.SetActive(false);
    }
    void reqTop()//请求排行榜
    {
       
        try
        {
             WebRequest req = HttpWebRequest.Create(ip);
            //修改请求头 会返回不同的排行榜
            req.Method = "fkfmg";//像素鸟为  "xsn" 
            req.BeginGetResponse(ResponseCallBack, req);
        }
        catch 
        {
              return;
        }
       
    }

    private void ResponseCallBack(System.IAsyncResult result)//请求完成后将请求的信息放置在字符串 content 中
    {
        // print("进入查询 0");
        try
        {
            HttpWebRequest hwq = (HttpWebRequest)result.AsyncState;
            WebResponse webRespomse = hwq.EndGetResponse(result);
            Stream strem = webRespomse.GetResponseStream();
            StreamReader reader = new StreamReader(strem);
            content = reader.ReadToEnd();
        }
        catch
        {

            return;
        }

    }


   public void   posIsError()
    {
        if (!responsIsSure)
        {
            windowInset.SetActive(true);
            playerPrefer.subNumder = 0;
            PlayerPrefs.SetInt("subNumder",0);
        }
        else
        {
            insertBtn.gameObject.SetActive(false);
        }
    }

   public void POSTClick()
   {
       if (inputName.text == null || inputName.text == string.Empty || inputName.text == "" || inputName.text.Length>20)
       {
           inputError.SetActive(true);
           return;
       }
       name = inputName.text;
       count = playerPrefer.count;

       loding.SetActive(true);
       responsIsSure = false;
      
        str = "fkfmg|" + name + "|" + count;;
        Invoke("posIsError",5f);
        try
        {
            insertBtn.enabled = false;
            WebRequest req = HttpWebRequest.Create(ip);
            req.Method = "POST";
            req.BeginGetRequestStream(PostResponseCallBack, req);  
        }
        catch 
        {
         //   message.text = "Post发生异常";

        }
      //  message.text = "进入回掉";
    }
    private void PostResponseCallBack(System.IAsyncResult result)
    {
        try
        {
            HttpWebRequest hwq = (HttpWebRequest)result.AsyncState;
            Stream webRespomse = hwq.EndGetRequestStream(result);
           // string postString = "fkfmg|qq1149375949|16";
            byte[] date = Encoding.UTF8.GetBytes(str);
            webRespomse.Write(date, 0, date.Length);
            webRespomse.Close();
            responsIsSure = true;
            hwq.BeginGetResponse(ResponseCallBack, hwq);
        }
        catch 
        {
           
        }
    }
    IEnumerator   eror()
    {

        window.SetActive(true);
        yield return new WaitForSeconds(3f);
        window.SetActive(false);
    }
   

    public  void messageDes() 
    {
        if (content == null || content == string.Empty || content=="")
        {
            StartCoroutine("eror");
            return;
        }
        string[] strArray = content.Split('|');
        for (int i = 0; i < strArray.Length-1; i++)
        {
//            print(strArray[i]);
            string[] temp = strArray[i].Split('*');
            GameObject GO = GameObject.Instantiate(PREFAB) as GameObject;
            GO.transform.parent = GRID.transform;
            GO.transform.localScale = Vector2.one;
            selfCCL self = GO.GetComponent<selfCCL>();
            self.TOP.text = " "+(i+1).ToString()+"st ";
            self.COUNT.text = temp[0];
            self.NAME.text = temp[1];
        }
    }
    public  void reLoad() 
    {
        label.gameObject.SetActive(true);
        Invoke("Showwindow", 4f); 
        content = null;
        selfCCL[]  selfs=GRID.transform.GetComponentsInChildren<selfCCL>();
        if (selfs==null)
        {
            return;
        }
        for (int i = 0; i < selfs.Length; i++)
        {
            Destroy(selfs[i].gameObject);
        }
        reqTop();
        Invoke("messageDes", 4f);
    }
}
